package com.bookstore.servlet;

import com.bookstore.pojo.*;
import com.bookstore.services.Impl.OrderServiceImpl;
import com.bookstore.services.Impl.UserServiceImpl;
import com.bookstore.services.OrderService;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "OrderClientServlet", value = "/OrderClientServlet")
public class OrderClientServlet extends BaseServlet {
    private Gson gson=new Gson();
    private OrderService orderService=new OrderServiceImpl();
    private UserServiceImpl userService=new UserServiceImpl();

    protected void checkout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String readLine = request.getReader().readLine();
        User user = gson.fromJson(readLine, User.class);
        if(user!=null){
            System.out.println("购物："+user);
            Cart cart = (Cart) session.getAttribute("cart");
            System.out.println("购物："+cart);
            String orderId = orderService.checkout(cart, user);
            response.getWriter().write(orderId);
            session.removeAttribute("cart");
        }
    }

    protected void accept(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String readLine = request.getReader().readLine();
        Order order = gson.fromJson(readLine, Order.class);
        orderService.updateStatus(order.getOrderId(),Contants.DELIVERED+"");
        System.out.println("收货");
    }
    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Order> allOrder = orderService.getAllOrder();
        String toJson = gson.toJson(allOrder);
        response.getWriter().write(toJson);
    }

    protected void details(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String orderId = request.getParameter("orderId");
        OrderItem myOrder = orderService.getMyOrder(orderId);
        String toJson = gson.toJson(myOrder);
        response.getWriter().write(toJson);
    }


    protected void send(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String readLine = request.getReader().readLine();
        System.out.println(readLine);
        Order order = gson.fromJson(readLine, Order.class);
        orderService.updateStatus(order.getOrderId(),Contants.DELIVER+"");
        System.out.println("发货");
    }
}
